#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
桥接模式 (Bridge Pattern) - Python实现详解

桥接模式是一种结构设计模式，它将抽象部分与它的实现部分分离，使它们都可以独立地变化。
桥接模式通过组合而不是继承来连接抽象和实现，提供了更大的灵活性。

与Java对比：
1. Python的多重继承提供了更灵活的实现方式
2. Python的duck typing减少了接口定义的需要
3. Python的装饰器可以实现动态桥接
4. Python的元类可以实现更高级的桥接功能

作者: Assistant
日期: 2024
"""

import time
import threading
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Callable, Union, Protocol
from dataclasses import dataclass
from enum import Enum
import json
import logging
from contextlib import contextmanager


# ============================================================================
# 1. 传统桥接模式实现
# ============================================================================

class DrawingAPI(ABC):
    """
    实现接口
    定义了实现类的接口，这个接口不一定要与抽象类的接口完全一致
    """
    
    @abstractmethod
    def draw_circle(self, x: float, y: float, radius: float) -> None:
        """绘制圆形"""
        pass
    
    @abstractmethod
    def draw_rectangle(self, x: float, y: float, width: float, height: float) -> None:
        """绘制矩形"""
        pass
    
    @abstractmethod
    def draw_line(self, x1: float, y1: float, x2: float, y2: float) -> None:
        """绘制直线"""
        pass
    
    @abstractmethod
    def set_color(self, color: str) -> None:
        """设置颜色"""
        pass


class CanvasAPI(DrawingAPI):
    """
    Canvas实现
    具体实现类，实现了DrawingAPI接口
    """
    
    def __init__(self, name: str = "Canvas"):
        self.name = name
        self.current_color = "black"
        self.operations: List[str] = []
    
    def draw_circle(self, x: float, y: float, radius: float) -> None:
        """在Canvas上绘制圆形"""
        operation = f"Canvas.drawCircle({x}, {y}, {radius}) with color {self.current_color}"
        self.operations.append(operation)
        print(f"{self.name}: {operation}")
    
    def draw_rectangle(self, x: float, y: float, width: float, height: float) -> None:
        """在Canvas上绘制矩形"""
        operation = f"Canvas.drawRect({x}, {y}, {width}, {height}) with color {self.current_color}"
        self.operations.append(operation)
        print(f"{self.name}: {operation}")
    
    def draw_line(self, x1: float, y1: float, x2: float, y2: float) -> None:
        """在Canvas上绘制直线"""
        operation = f"Canvas.drawLine({x1}, {y1}, {x2}, {y2}) with color {self.current_color}"
        self.operations.append(operation)
        print(f"{self.name}: {operation}")
    
    def set_color(self, color: str) -> None:
        """设置Canvas颜色"""
        self.current_color = color
        print(f"{self.name}: Set color to {color}")
    
    def get_operations(self) -> List[str]:
        """获取所有操作记录"""
        return self.operations.copy()


class SVGAPI(DrawingAPI):
    """
    SVG实现
    另一个具体实现类
    """
    
    def __init__(self, name: str = "SVG"):
        self.name = name
        self.current_color = "black"
        self.svg_elements: List[str] = []
    
    def draw_circle(self, x: float, y: float, radius: float) -> None:
        """生成SVG圆形元素"""
        element = f'<circle cx="{x}" cy="{y}" r="{radius}" fill="{self.current_color}" />'
        self.svg_elements.append(element)
        print(f"{self.name}: {element}")
    
    def draw_rectangle(self, x: float, y: float, width: float, height: float) -> None:
        """生成SVG矩形元素"""
        element = f'<rect x="{x}" y="{y}" width="{width}" height="{height}" fill="{self.current_color}" />'
        self.svg_elements.append(element)
        print(f"{self.name}: {element}")
    
    def draw_line(self, x1: float, y1: float, x2: float, y2: float) -> None:
        """生成SVG直线元素"""
        element = f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{self.current_color}" />'
        self.svg_elements.append(element)
        print(f"{self.name}: {element}")
    
    def set_color(self, color: str) -> None:
        """设置SVG颜色"""
        self.current_color = color
        print(f"{self.name}: Set color to {color}")
    
    def get_svg(self) -> str:
        """获取完整的SVG代码"""
        svg_content = '\n'.join(self.svg_elements)
        return f'<svg>\n{svg_content}\n</svg>'


class OpenGLAPI(DrawingAPI):
    """
    OpenGL实现
    第三个具体实现类
    """
    
    def __init__(self, name: str = "OpenGL"):
        self.name = name
        self.current_color = "black"
        self.gl_commands: List[str] = []
    
    def draw_circle(self, x: float, y: float, radius: float) -> None:
        """生成OpenGL圆形绘制命令"""
        commands = [
            f"glColor({self.current_color})",
            f"glBegin(GL_TRIANGLE_FAN)",
            f"glVertex2f({x}, {y})",
            f"// Draw circle with radius {radius}",
            f"glEnd()"
        ]
        self.gl_commands.extend(commands)
        print(f"{self.name}: Draw circle at ({x}, {y}) with radius {radius}")
    
    def draw_rectangle(self, x: float, y: float, width: float, height: float) -> None:
        """生成OpenGL矩形绘制命令"""
        commands = [
            f"glColor({self.current_color})",
            f"glBegin(GL_QUADS)",
            f"glVertex2f({x}, {y})",
            f"glVertex2f({x + width}, {y})",
            f"glVertex2f({x + width}, {y + height})",
            f"glVertex2f({x}, {y + height})",
            f"glEnd()"
        ]
        self.gl_commands.extend(commands)
        print(f"{self.name}: Draw rectangle at ({x}, {y}) size {width}x{height}")
    
    def draw_line(self, x1: float, y1: float, x2: float, y2: float) -> None:
        """生成OpenGL直线绘制命令"""
        commands = [
            f"glColor({self.current_color})",
            f"glBegin(GL_LINES)",
            f"glVertex2f({x1}, {y1})",
            f"glVertex2f({x2}, {y2})",
            f"glEnd()"
        ]
        self.gl_commands.extend(commands)
        print(f"{self.name}: Draw line from ({x1}, {y1}) to ({x2}, {y2})")
    
    def set_color(self, color: str) -> None:
        """设置OpenGL颜色"""
        self.current_color = color
        print(f"{self.name}: Set color to {color}")
    
    def get_commands(self) -> List[str]:
        """获取所有OpenGL命令"""
        return self.gl_commands.copy()


class Shape(ABC):
    """
    抽象类
    定义了抽象类的接口，并保存一个对实现对象的引用
    """
    
    def __init__(self, drawing_api: DrawingAPI):
        self._drawing_api = drawing_api
    
    @abstractmethod
    def draw(self) -> None:
        """绘制形状"""
        pass
    
    @abstractmethod
    def resize(self, factor: float) -> None:
        """调整大小"""
        pass
    
    def set_color(self, color: str) -> None:
        """设置颜色"""
        self._drawing_api.set_color(color)


class Circle(Shape):
    """
    扩展抽象类
    圆形实现
    """
    
    def __init__(self, x: float, y: float, radius: float, drawing_api: DrawingAPI):
        super().__init__(drawing_api)
        self._x = x
        self._y = y
        self._radius = radius
    
    def draw(self) -> None:
        """绘制圆形"""
        self._drawing_api.draw_circle(self._x, self._y, self._radius)
    
    def resize(self, factor: float) -> None:
        """调整圆形大小"""
        self._radius *= factor
        print(f"Circle resized by factor {factor}, new radius: {self._radius}")
    
    def get_area(self) -> float:
        """计算圆形面积"""
        return 3.14159 * self._radius * self._radius
    
    def move(self, dx: float, dy: float) -> None:
        """移动圆形"""
        self._x += dx
        self._y += dy
        print(f"Circle moved by ({dx}, {dy}), new position: ({self._x}, {self._y})")


class Rectangle(Shape):
    """
    扩展抽象类
    矩形实现
    """
    
    def __init__(self, x: float, y: float, width: float, height: float, drawing_api: DrawingAPI):
        super().__init__(drawing_api)
        self._x = x
        self._y = y
        self._width = width
        self._height = height
    
    def draw(self) -> None:
        """绘制矩形"""
        self._drawing_api.draw_rectangle(self._x, self._y, self._width, self._height)
    
    def resize(self, factor: float) -> None:
        """调整矩形大小"""
        self._width *= factor
        self._height *= factor
        print(f"Rectangle resized by factor {factor}, new size: {self._width}x{self._height}")
    
    def get_area(self) -> float:
        """计算矩形面积"""
        return self._width * self._height
    
    def move(self, dx: float, dy: float) -> None:
        """移动矩形"""
        self._x += dx
        self._y += dy
        print(f"Rectangle moved by ({dx}, {dy}), new position: ({self._x}, {self._y})")


# ============================================================================
# 2. 消息传递桥接模式
# ============================================================================

class MessageSender(ABC):
    """
    消息发送接口
    定义了消息发送的实现接口
    """
    
    @abstractmethod
    def send_message(self, recipient: str, message: str) -> bool:
        """发送消息"""
        pass
    
    @abstractmethod
    def get_delivery_status(self, message_id: str) -> str:
        """获取投递状态"""
        pass


class EmailSender(MessageSender):
    """
    邮件发送实现
    """
    
    def __init__(self, smtp_server: str = "smtp.example.com"):
        self.smtp_server = smtp_server
        self.sent_messages: Dict[str, Dict] = {}
        self.message_counter = 0
    
    def send_message(self, recipient: str, message: str) -> bool:
        """发送邮件"""
        self.message_counter += 1
        message_id = f"email_{self.message_counter}"
        
        # 模拟邮件发送
        print(f"Email: Sending to {recipient} via {self.smtp_server}")
        print(f"Email: Subject: Message from System")
        print(f"Email: Body: {message}")
        
        # 记录发送信息
        self.sent_messages[message_id] = {
            "recipient": recipient,
            "message": message,
            "status": "delivered",
            "timestamp": time.time()
        }
        
        print(f"Email: Message sent successfully, ID: {message_id}")
        return True
    
    def get_delivery_status(self, message_id: str) -> str:
        """获取邮件投递状态"""
        if message_id in self.sent_messages:
            return self.sent_messages[message_id]["status"]
        return "not_found"
    
    def get_sent_count(self) -> int:
        """获取已发送邮件数量"""
        return len(self.sent_messages)


class SMSSender(MessageSender):
    """
    短信发送实现
    """
    
    def __init__(self, provider: str = "SMS Provider"):
        self.provider = provider
        self.sent_messages: Dict[str, Dict] = {}
        self.message_counter = 0
    
    def send_message(self, recipient: str, message: str) -> bool:
        """发送短信"""
        self.message_counter += 1
        message_id = f"sms_{self.message_counter}"
        
        # 模拟短信发送
        print(f"SMS: Sending to {recipient} via {self.provider}")
        print(f"SMS: Message: {message[:160]}...")  # 短信长度限制
        
        # 记录发送信息
        self.sent_messages[message_id] = {
            "recipient": recipient,
            "message": message,
            "status": "delivered",
            "timestamp": time.time()
        }
        
        print(f"SMS: Message sent successfully, ID: {message_id}")
        return True
    
    def get_delivery_status(self, message_id: str) -> str:
        """获取短信投递状态"""
        if message_id in self.sent_messages:
            return self.sent_messages[message_id]["status"]
        return "not_found"
    
    def get_sent_count(self) -> int:
        """获取已发送短信数量"""
        return len(self.sent_messages)


class PushNotificationSender(MessageSender):
    """
    推送通知发送实现
    """
    
    def __init__(self, service: str = "FCM"):
        self.service = service
        self.sent_messages: Dict[str, Dict] = {}
        self.message_counter = 0
    
    def send_message(self, recipient: str, message: str) -> bool:
        """发送推送通知"""
        self.message_counter += 1
        message_id = f"push_{self.message_counter}"
        
        # 模拟推送通知发送
        print(f"Push: Sending to device {recipient} via {self.service}")
        print(f"Push: Notification: {message}")
        
        # 记录发送信息
        self.sent_messages[message_id] = {
            "recipient": recipient,
            "message": message,
            "status": "delivered",
            "timestamp": time.time()
        }
        
        print(f"Push: Notification sent successfully, ID: {message_id}")
        return True
    
    def get_delivery_status(self, message_id: str) -> str:
        """获取推送通知投递状态"""
        if message_id in self.sent_messages:
            return self.sent_messages[message_id]["status"]
        return "not_found"
    
    def get_sent_count(self) -> int:
        """获取已发送推送通知数量"""
        return len(self.sent_messages)


class Message(ABC):
    """
    消息抽象类
    定义了消息的抽象接口
    """
    
    def __init__(self, sender: MessageSender):
        self._sender = sender
    
    @abstractmethod
    def send(self, recipient: str) -> bool:
        """发送消息"""
        pass


class TextMessage(Message):
    """
    文本消息
    """
    
    def __init__(self, content: str, sender: MessageSender):
        super().__init__(sender)
        self._content = content
    
    def send(self, recipient: str) -> bool:
        """发送文本消息"""
        print(f"TextMessage: Preparing to send text message")
        return self._sender.send_message(recipient, self._content)
    
    def get_content(self) -> str:
        """获取消息内容"""
        return self._content


class AlertMessage(Message):
    """
    警告消息
    """
    
    def __init__(self, alert_level: str, content: str, sender: MessageSender):
        super().__init__(sender)
        self._alert_level = alert_level
        self._content = content
    
    def send(self, recipient: str) -> bool:
        """发送警告消息"""
        print(f"AlertMessage: Preparing to send {self._alert_level} alert")
        formatted_message = f"[{self._alert_level.upper()}] {self._content}"
        return self._sender.send_message(recipient, formatted_message)
    
    def get_alert_level(self) -> str:
        """获取警告级别"""
        return self._alert_level


class RichMessage(Message):
    """
    富文本消息
    """
    
    def __init__(self, title: str, content: str, attachments: List[str], sender: MessageSender):
        super().__init__(sender)
        self._title = title
        self._content = content
        self._attachments = attachments
    
    def send(self, recipient: str) -> bool:
        """发送富文本消息"""
        print(f"RichMessage: Preparing to send rich message with {len(self._attachments)} attachments")
        
        # 格式化富文本消息
        formatted_message = f"Title: {self._title}\n\nContent: {self._content}"
        if self._attachments:
            formatted_message += f"\n\nAttachments: {', '.join(self._attachments)}"
        
        return self._sender.send_message(recipient, formatted_message)
    
    def add_attachment(self, attachment: str) -> None:
        """添加附件"""
        self._attachments.append(attachment)
        print(f"RichMessage: Added attachment: {attachment}")


# ============================================================================
# 3. 数据库桥接模式
# ============================================================================

class DatabaseDriver(ABC):
    """
    数据库驱动接口
    定义了数据库操作的实现接口
    """
    
    @abstractmethod
    def connect(self, connection_string: str) -> bool:
        """连接数据库"""
        pass
    
    @abstractmethod
    def execute_query(self, query: str) -> List[Dict[str, Any]]:
        """执行查询"""
        pass
    
    @abstractmethod
    def execute_update(self, query: str) -> int:
        """执行更新"""
        pass
    
    @abstractmethod
    def close(self) -> None:
        """关闭连接"""
        pass


class MySQLDriver(DatabaseDriver):
    """
    MySQL数据库驱动
    """
    
    def __init__(self):
        self.connected = False
        self.connection_string = ""
        self.query_count = 0
    
    def connect(self, connection_string: str) -> bool:
        """连接MySQL数据库"""
        print(f"MySQL: Connecting to {connection_string}")
        self.connection_string = connection_string
        self.connected = True
        print("MySQL: Connected successfully")
        return True
    
    def execute_query(self, query: str) -> List[Dict[str, Any]]:
        """执行MySQL查询"""
        if not self.connected:
            raise RuntimeError("MySQL: Not connected to database")
        
        self.query_count += 1
        print(f"MySQL: Executing query: {query}")
        
        # 模拟查询结果
        if "SELECT" in query.upper():
            return [
                {"id": 1, "name": "MySQL User 1", "email": "user1@mysql.com"},
                {"id": 2, "name": "MySQL User 2", "email": "user2@mysql.com"}
            ]
        return []
    
    def execute_update(self, query: str) -> int:
        """执行MySQL更新"""
        if not self.connected:
            raise RuntimeError("MySQL: Not connected to database")
        
        self.query_count += 1
        print(f"MySQL: Executing update: {query}")
        
        # 模拟更新结果
        return 1  # 影响的行数
    
    def close(self) -> None:
        """关闭MySQL连接"""
        if self.connected:
            print("MySQL: Closing connection")
            self.connected = False
    
    def get_query_count(self) -> int:
        """获取查询次数"""
        return self.query_count


class PostgreSQLDriver(DatabaseDriver):
    """
    PostgreSQL数据库驱动
    """
    
    def __init__(self):
        self.connected = False
        self.connection_string = ""
        self.query_count = 0
    
    def connect(self, connection_string: str) -> bool:
        """连接PostgreSQL数据库"""
        print(f"PostgreSQL: Connecting to {connection_string}")
        self.connection_string = connection_string
        self.connected = True
        print("PostgreSQL: Connected successfully")
        return True
    
    def execute_query(self, query: str) -> List[Dict[str, Any]]:
        """执行PostgreSQL查询"""
        if not self.connected:
            raise RuntimeError("PostgreSQL: Not connected to database")
        
        self.query_count += 1
        print(f"PostgreSQL: Executing query: {query}")
        
        # 模拟查询结果
        if "SELECT" in query.upper():
            return [
                {"id": 1, "name": "PostgreSQL User 1", "email": "user1@postgres.com"},
                {"id": 2, "name": "PostgreSQL User 2", "email": "user2@postgres.com"}
            ]
        return []
    
    def execute_update(self, query: str) -> int:
        """执行PostgreSQL更新"""
        if not self.connected:
            raise RuntimeError("PostgreSQL: Not connected to database")
        
        self.query_count += 1
        print(f"PostgreSQL: Executing update: {query}")
        
        # 模拟更新结果
        return 1  # 影响的行数
    
    def close(self) -> None:
        """关闭PostgreSQL连接"""
        if self.connected:
            print("PostgreSQL: Closing connection")
            self.connected = False
    
    def get_query_count(self) -> int:
        """获取查询次数"""
        return self.query_count


class MongoDBDriver(DatabaseDriver):
    """
    MongoDB数据库驱动
    """
    
    def __init__(self):
        self.connected = False
        self.connection_string = ""
        self.query_count = 0
    
    def connect(self, connection_string: str) -> bool:
        """连接MongoDB数据库"""
        print(f"MongoDB: Connecting to {connection_string}")
        self.connection_string = connection_string
        self.connected = True
        print("MongoDB: Connected successfully")
        return True
    
    def execute_query(self, query: str) -> List[Dict[str, Any]]:
        """执行MongoDB查询"""
        if not self.connected:
            raise RuntimeError("MongoDB: Not connected to database")
        
        self.query_count += 1
        print(f"MongoDB: Executing query: {query}")
        
        # 模拟查询结果
        if "find" in query.lower():
            return [
                {"_id": "507f1f77bcf86cd799439011", "name": "MongoDB User 1", "email": "user1@mongo.com"},
                {"_id": "507f1f77bcf86cd799439012", "name": "MongoDB User 2", "email": "user2@mongo.com"}
            ]
        return []
    
    def execute_update(self, query: str) -> int:
        """执行MongoDB更新"""
        if not self.connected:
            raise RuntimeError("MongoDB: Not connected to database")
        
        self.query_count += 1
        print(f"MongoDB: Executing update: {query}")
        
        # 模拟更新结果
        return 1  # 影响的文档数
    
    def close(self) -> None:
        """关闭MongoDB连接"""
        if self.connected:
            print("MongoDB: Closing connection")
            self.connected = False
    
    def get_query_count(self) -> int:
        """获取查询次数"""
        return self.query_count


class Database(ABC):
    """
    数据库抽象类
    定义了数据库操作的抽象接口
    """
    
    def __init__(self, driver: DatabaseDriver):
        self._driver = driver
    
    @abstractmethod
    def find_users(self) -> List[Dict[str, Any]]:
        """查找用户"""
        pass
    
    @abstractmethod
    def create_user(self, name: str, email: str) -> bool:
        """创建用户"""
        pass
    
    def connect(self, connection_string: str) -> bool:
        """连接数据库"""
        return self._driver.connect(connection_string)
    
    def close(self) -> None:
        """关闭数据库连接"""
        self._driver.close()


class UserDatabase(Database):
    """
    用户数据库
    具体的数据库实现
    """
    
    def find_users(self) -> List[Dict[str, Any]]:
        """查找所有用户"""
        print("UserDatabase: Finding all users")
        query = "SELECT * FROM users"
        return self._driver.execute_query(query)
    
    def create_user(self, name: str, email: str) -> bool:
        """创建新用户"""
        print(f"UserDatabase: Creating user {name} with email {email}")
        query = f"INSERT INTO users (name, email) VALUES ('{name}', '{email}')"
        affected_rows = self._driver.execute_update(query)
        return affected_rows > 0
    
    def find_user_by_email(self, email: str) -> Optional[Dict[str, Any]]:
        """根据邮箱查找用户"""
        print(f"UserDatabase: Finding user by email {email}")
        query = f"SELECT * FROM users WHERE email = '{email}'"
        results = self._driver.execute_query(query)
        return results[0] if results else None
    
    def update_user(self, user_id: int, name: str, email: str) -> bool:
        """更新用户信息"""
        print(f"UserDatabase: Updating user {user_id}")
        query = f"UPDATE users SET name = '{name}', email = '{email}' WHERE id = {user_id}"
        affected_rows = self._driver.execute_update(query)
        return affected_rows > 0


class ProductDatabase(Database):
    """
    产品数据库
    另一个具体的数据库实现
    """
    
    def find_users(self) -> List[Dict[str, Any]]:
        """查找所有产品（这里为了接口一致性）"""
        print("ProductDatabase: Finding all products")
        query = "SELECT * FROM products"
        return self._driver.execute_query(query)
    
    def create_user(self, name: str, email: str) -> bool:
        """创建新产品（这里为了接口一致性）"""
        print(f"ProductDatabase: Creating product {name}")
        query = f"INSERT INTO products (name, description) VALUES ('{name}', '{email}')"
        affected_rows = self._driver.execute_update(query)
        return affected_rows > 0
    
    def find_products_by_category(self, category: str) -> List[Dict[str, Any]]:
        """根据分类查找产品"""
        print(f"ProductDatabase: Finding products by category {category}")
        query = f"SELECT * FROM products WHERE category = '{category}'"
        return self._driver.execute_query(query)
    
    def update_product_price(self, product_id: int, price: float) -> bool:
        """更新产品价格"""
        print(f"ProductDatabase: Updating product {product_id} price to {price}")
        query = f"UPDATE products SET price = {price} WHERE id = {product_id}"
        affected_rows = self._driver.execute_update(query)
        return affected_rows > 0


# ============================================================================
# 4. 装饰器桥接模式
# ============================================================================

def bridge_decorator(implementation_class):
    """
    桥接装饰器
    动态地为类添加实现
    """
    def decorator(abstraction_class):
        class BridgedClass(abstraction_class):
            def __init__(self, *args, **kwargs):
                # 创建实现实例
                self._implementation = implementation_class()
                super().__init__(*args, **kwargs)
            
            def get_implementation(self):
                return self._implementation
        
        return BridgedClass
    
    return decorator


class LoggingImplementation:
    """
    日志记录实现
    """
    
    def __init__(self):
        self.logs: List[str] = []
    
    def log(self, message: str) -> None:
        """记录日志"""
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"[{timestamp}] {message}"
        self.logs.append(log_entry)
        print(f"Log: {log_entry}")
    
    def get_logs(self) -> List[str]:
        """获取所有日志"""
        return self.logs.copy()


class CachingImplementation:
    """
    缓存实现
    """
    
    def __init__(self):
        self.cache: Dict[str, Any] = {}
        self.hit_count = 0
        self.miss_count = 0
    
    def get(self, key: str) -> Optional[Any]:
        """从缓存获取数据"""
        if key in self.cache:
            self.hit_count += 1
            print(f"Cache: Hit for key '{key}'")
            return self.cache[key]
        else:
            self.miss_count += 1
            print(f"Cache: Miss for key '{key}'")
            return None
    
    def put(self, key: str, value: Any) -> None:
        """向缓存存储数据"""
        self.cache[key] = value
        print(f"Cache: Stored key '{key}'")
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计"""
        total = self.hit_count + self.miss_count
        hit_rate = (self.hit_count / total * 100) if total > 0 else 0
        return {
            "hits": self.hit_count,
            "misses": self.miss_count,
            "hit_rate": f"{hit_rate:.1f}%",
            "cache_size": len(self.cache)
        }


@bridge_decorator(LoggingImplementation)
class ServiceWithLogging:
    """
    带日志记录的服务
    """
    
    def __init__(self, name: str):
        self.name = name
    
    def process_request(self, request: str) -> str:
        """处理请求"""
        self._implementation.log(f"Service {self.name}: Processing request '{request}'")
        
        # 模拟处理
        result = f"Processed: {request}"
        
        self._implementation.log(f"Service {self.name}: Request processed successfully")
        return result
    
    def get_service_logs(self) -> List[str]:
        """获取服务日志"""
        return self._implementation.get_logs()


@bridge_decorator(CachingImplementation)
class ServiceWithCaching:
    """
    带缓存的服务
    """
    
    def __init__(self, name: str):
        self.name = name
        self.process_count = 0
    
    def get_data(self, key: str) -> str:
        """获取数据（带缓存）"""
        # 先尝试从缓存获取
        cached_data = self._implementation.get(key)
        if cached_data is not None:
            return cached_data
        
        # 缓存未命中，生成数据
        self.process_count += 1
        data = f"Data for {key} (generated #{self.process_count})"
        
        # 存入缓存
        self._implementation.put(key, data)
        
        return data
    
    def get_cache_stats(self) -> Dict[str, Any]:
        """获取缓存统计"""
        stats = self._implementation.get_stats()
        stats["process_count"] = self.process_count
        return stats


# ============================================================================
# 5. 演示函数
# ============================================================================

def demonstrate_basic_bridge():
    """
    演示基本桥接模式
    """
    print("\n=== 基本桥接模式演示 ===")
    
    # 创建不同的绘图API实现
    canvas_api = CanvasAPI("HTML5 Canvas")
    svg_api = SVGAPI("SVG Graphics")
    opengl_api = OpenGLAPI("OpenGL 3D")
    
    print("\n=== 使用Canvas API绘制图形 ===")
    
    # 使用Canvas API创建图形
    circle1 = Circle(100, 100, 50, canvas_api)
    rect1 = Rectangle(200, 200, 100, 80, canvas_api)
    
    # 设置颜色并绘制
    circle1.set_color("red")
    circle1.draw()
    circle1.resize(1.5)
    circle1.draw()
    
    rect1.set_color("blue")
    rect1.draw()
    rect1.move(50, 50)
    rect1.draw()
    
    print(f"\nCanvas操作记录: {len(canvas_api.get_operations())}条")
    
    print("\n=== 使用SVG API绘制相同图形 ===")
    
    # 使用SVG API创建相同的图形
    circle2 = Circle(100, 100, 50, svg_api)
    rect2 = Rectangle(200, 200, 100, 80, svg_api)
    
    circle2.set_color("green")
    circle2.draw()
    
    rect2.set_color("yellow")
    rect2.draw()
    
    print(f"\nSVG代码:\n{svg_api.get_svg()}")
    
    print("\n=== 使用OpenGL API绘制图形 ===")
    
    # 使用OpenGL API创建图形
    circle3 = Circle(100, 100, 50, opengl_api)
    
    circle3.set_color("purple")
    circle3.draw()
    
    print(f"\nOpenGL命令数: {len(opengl_api.get_commands())}")


def demonstrate_message_bridge():
    """
    演示消息传递桥接模式
    """
    print("\n=== 消息传递桥接模式演示 ===")
    
    # 创建不同的消息发送实现
    email_sender = EmailSender("smtp.company.com")
    sms_sender = SMSSender("Twilio SMS")
    push_sender = PushNotificationSender("Firebase FCM")
    
    print("\n=== 发送文本消息 ===")
    
    # 使用不同的发送方式发送文本消息
    text_msg_email = TextMessage("Hello from email!", email_sender)
    text_msg_sms = TextMessage("Hello from SMS!", sms_sender)
    text_msg_push = TextMessage("Hello from push!", push_sender)
    
    text_msg_email.send("user@example.com")
    text_msg_sms.send("+1234567890")
    text_msg_push.send("device_token_123")
    
    print("\n=== 发送警告消息 ===")
    
    # 发送不同级别的警告消息
    alert_email = AlertMessage("critical", "System overload detected!", email_sender)
    alert_sms = AlertMessage("warning", "High CPU usage", sms_sender)
    alert_push = AlertMessage("info", "Backup completed", push_sender)
    
    alert_email.send("admin@example.com")
    alert_sms.send("+1234567890")
    alert_push.send("admin_device_token")
    
    print("\n=== 发送富文本消息 ===")
    
    # 发送富文本消息
    rich_msg = RichMessage(
        "Monthly Report",
        "Please find the monthly report attached.",
        ["report.pdf", "charts.xlsx"],
        email_sender
    )
    
    rich_msg.add_attachment("summary.docx")
    rich_msg.send("manager@example.com")
    
    # 显示发送统计
    print("\n=== 发送统计 ===")
    print(f"邮件发送数: {email_sender.get_sent_count()}")
    print(f"短信发送数: {sms_sender.get_sent_count()}")
    print(f"推送发送数: {push_sender.get_sent_count()}")


def demonstrate_database_bridge():
    """
    演示数据库桥接模式
    """
    print("\n=== 数据库桥接模式演示 ===")
    
    # 创建不同的数据库驱动
    mysql_driver = MySQLDriver()
    postgres_driver = PostgreSQLDriver()
    mongo_driver = MongoDBDriver()
    
    print("\n=== 使用MySQL数据库 ===")
    
    # 使用MySQL驱动的用户数据库
    user_db_mysql = UserDatabase(mysql_driver)
    user_db_mysql.connect("mysql://localhost:3306/userdb")
    
    # 执行数据库操作
    users = user_db_mysql.find_users()
    print(f"找到 {len(users)} 个用户")
    
    user_db_mysql.create_user("Alice", "alice@example.com")
    user_db_mysql.update_user(1, "Alice Smith", "alice.smith@example.com")
    
    user_db_mysql.close()
    print(f"MySQL查询次数: {mysql_driver.get_query_count()}")
    
    print("\n=== 使用PostgreSQL数据库 ===")
    
    # 使用PostgreSQL驱动的用户数据库
    user_db_postgres = UserDatabase(postgres_driver)
    user_db_postgres.connect("postgresql://localhost:5432/userdb")
    
    users = user_db_postgres.find_users()
    print(f"找到 {len(users)} 个用户")
    
    user_db_postgres.create_user("Bob", "bob@example.com")
    
    user_db_postgres.close()
    print(f"PostgreSQL查询次数: {postgres_driver.get_query_count()}")
    
    print("\n=== 使用MongoDB数据库 ===")
    
    # 使用MongoDB驱动的产品数据库
    product_db_mongo = ProductDatabase(mongo_driver)
    product_db_mongo.connect("mongodb://localhost:27017/productdb")
    
    products = product_db_mongo.find_users()  # 这里实际是查找产品
    print(f"找到 {len(products)} 个产品")
    
    product_db_mongo.create_user("Laptop", "High-performance laptop")  # 这里实际是创建产品
    product_db_mongo.update_product_price(1, 999.99)
    
    product_db_mongo.close()
    print(f"MongoDB查询次数: {mongo_driver.get_query_count()}")


def demonstrate_decorator_bridge():
    """
    演示装饰器桥接模式
    """
    print("\n=== 装饰器桥接模式演示 ===")
    
    print("\n=== 带日志记录的服务 ===")
    
    # 创建带日志记录的服务
    logging_service = ServiceWithLogging("UserService")
    
    # 处理请求
    result1 = logging_service.process_request("get_user_profile")
    result2 = logging_service.process_request("update_user_info")
    
    print(f"\n处理结果1: {result1}")
    print(f"处理结果2: {result2}")
    
    # 显示日志
    print("\n=== 服务日志 ===")
    logs = logging_service.get_service_logs()
    for log in logs:
        print(log)
    
    print("\n=== 带缓存的服务 ===")
    
    # 创建带缓存的服务
    caching_service = ServiceWithCaching("DataService")
    
    # 多次获取相同数据
    print("\n--- 首次获取数据 ---")
    data1 = caching_service.get_data("user_123")
    print(f"数据: {data1}")
    
    print("\n--- 再次获取相同数据 ---")
    data2 = caching_service.get_data("user_123")
    print(f"数据: {data2}")
    
    print("\n--- 获取不同数据 ---")
    data3 = caching_service.get_data("user_456")
    print(f"数据: {data3}")
    
    print("\n--- 再次获取第一个数据 ---")
    data4 = caching_service.get_data("user_123")
    print(f"数据: {data4}")
    
    # 显示缓存统计
    print("\n=== 缓存统计 ===")
    stats = caching_service.get_cache_stats()
    for key, value in stats.items():
        print(f"{key}: {value}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    num_operations = 1000
    
    print(f"\n=== 测试 {num_operations} 次图形绘制操作 ===")
    
    # 测试Canvas API性能
    print("\n--- Canvas API性能测试 ---")
    canvas_api = CanvasAPI("Performance Test Canvas")
    
    start_time = time.time()
    for i in range(num_operations):
        circle = Circle(i % 500, i % 500, 10, canvas_api)
        circle.set_color("red" if i % 2 == 0 else "blue")
        circle.draw()
    canvas_time = time.time() - start_time
    
    print(f"Canvas API总时间: {canvas_time:.3f}秒")
    print(f"平均每次操作: {canvas_time/num_operations*1000:.3f}毫秒")
    print(f"Canvas操作数: {len(canvas_api.get_operations())}")
    
    # 测试SVG API性能
    print("\n--- SVG API性能测试 ---")
    svg_api = SVGAPI("Performance Test SVG")
    
    start_time = time.time()
    for i in range(num_operations):
        circle = Circle(i % 500, i % 500, 10, svg_api)
        circle.set_color("green" if i % 2 == 0 else "yellow")
        circle.draw()
    svg_time = time.time() - start_time
    
    print(f"SVG API总时间: {svg_time:.3f}秒")
    print(f"平均每次操作: {svg_time/num_operations*1000:.3f}毫秒")
    print(f"SVG元素数: {len(svg_api.svg_elements)}")
    
    # 性能对比
    print("\n=== 性能对比结果 ===")
    if canvas_time < svg_time:
        improvement = (svg_time - canvas_time) / svg_time * 100
        print(f"Canvas API比SVG API快 {improvement:.1f}%")
    else:
        improvement = (canvas_time - svg_time) / canvas_time * 100
        print(f"SVG API比Canvas API快 {improvement:.1f}%")
    
    print("\n=== 桥接模式的优势 ===")
    print("""
    桥接模式的性能优势:
    1. 运行时切换实现，无需重新编译
    2. 实现和抽象独立变化，降低耦合
    3. 可以针对不同场景选择最优实现
    4. 支持实现的热插拔和动态配置
    """)


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 桥接模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java桥接模式的实现:
    
    // Java实现接口
    public interface DrawingAPI {
        void drawCircle(double x, double y, double radius);
        void drawRectangle(double x, double y, double width, double height);
    }
    
    // Java具体实现
    public class CanvasAPI implements DrawingAPI {
        @Override
        public void drawCircle(double x, double y, double radius) {
            System.out.println("Canvas: Drawing circle at (" + x + ", " + y + ") with radius " + radius);
        }
        
        @Override
        public void drawRectangle(double x, double y, double width, double height) {
            System.out.println("Canvas: Drawing rectangle at (" + x + ", " + y + ") size " + width + "x" + height);
        }
    }
    
    // Java抽象类
    public abstract class Shape {
        protected DrawingAPI drawingAPI;
        
        protected Shape(DrawingAPI drawingAPI) {
            this.drawingAPI = drawingAPI;
        }
        
        public abstract void draw();
        public abstract void resize(double factor);
    }
    
    // Java具体抽象
    public class Circle extends Shape {
        private double x, y, radius;
        
        public Circle(double x, double y, double radius, DrawingAPI drawingAPI) {
            super(drawingAPI);
            this.x = x;
            this.y = y;
            this.radius = radius;
        }
        
        @Override
        public void draw() {
            drawingAPI.drawCircle(x, y, radius);
        }
        
        @Override
        public void resize(double factor) {
            radius *= factor;
        }
    }
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python桥接模式的优势:
    
    1. Duck Typing:
       - 不需要显式接口定义
       - 更灵活的类型系统
    
    2. 装饰器支持:
       - @bridge_decorator提供简洁的桥接实现
       - 可以动态添加桥接功能
    
    3. 多重继承:
       - 支持更复杂的继承结构
       - 可以组合多个实现
    
    4. 动态特性:
       - 运行时动态创建和修改类
       - 更灵活的桥接配置
    
    5. 上下文管理器:
       - with语句支持资源管理
       - 自动清理和初始化
    """)
    
    print("\n=== 实际应用场景对比 ===")
    print("""
    应用场景对比:
    
    Java适合:
    - 大型企业应用的架构设计
    - 需要严格类型检查的系统
    - 多团队协作的大型项目
    - 性能要求极高的系统
    
    Python适合:
    - 快速原型开发
    - 数据科学和机器学习
    - Web应用和API开发
    - 自动化脚本和工具
    - 需要灵活配置的系统
    """)


def main():
    """
    主函数 - 演示所有桥接模式实现
    """
    print("桥接模式 (Bridge Pattern) - Python实现演示")
    print("=" * 60)
    
    # 演示基本桥接模式
    demonstrate_basic_bridge()
    
    # 演示消息传递桥接模式
    demonstrate_message_bridge()
    
    # 演示数据库桥接模式
    demonstrate_database_bridge()
    
    # 演示装饰器桥接模式
    demonstrate_decorator_bridge()
    
    # 演示性能对比
    demonstrate_performance_comparison()
    
    # 演示Java对比
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    桥接模式的核心思想:
    1. 将抽象部分与实现部分分离，使它们可以独立变化
    2. 通过组合而不是继承来连接抽象和实现
    3. 提供了比继承更大的灵活性
    
    Python实现的特点:
    1. Duck typing减少了接口定义的需要
    2. 装饰器提供了简洁的桥接实现方式
    3. 多重继承支持更复杂的结构
    4. 动态特性支持运行时配置
    
    适用场景:
    - 需要在运行时切换实现
    - 抽象和实现都需要独立扩展
    - 避免抽象和实现之间的永久绑定
    - 需要在多个对象间共享实现
    - 图形系统、数据库驱动、消息传递系统
    """)


if __name__ == "__main__":
    main()